// 动静分离
import http from 'node:http'
import fs from 'node:fs'
import path from 'node:path'
import mime from 'mime'

const server = http.createServer((req, res) => {
    const { method, url } = req
    // 处理静态资源
    if (method == 'GET' && url.startsWith('/static')) {
        const staticPath = path.join(process.cwd(), url)  // 静态资源的路径
        fs.readFile(staticPath, (err, data) => {
            if(err) {  // 出错返回404
                res.writeHead(404, {
                    "content-type": "text/plain; charset=utf-8"
                })
                res.end('Not Found')
            } else {
                const mimeType = mime.getType(staticPath)  // 获取文件类型
                res.writeHead(200, {
                    // "content-type": "text/html; charset=utf-8"  // mime类型
                    // "content-type": "text/css; charset=utf-8"  // mime类型
                    "content-type": mimeType,  // mime类型
                    "cache-control": "public, max-age=31536000"  // 设置缓存，浏览器的缓存, 浏览器有自己的缓存策略
                })
                res.end(data)
            }
        })
    }
    // 动态资源
    if ((method == 'GET' || method == 'POST') && url == '/api') {
        // 业务逻辑
    }
})

server.listen(80, () => {
    console.log('server is running at http://localhost')
})